import { asyncRoutes, constantRoutes } from '@/router'
import { getUserPermission } from '@/api/permission'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// /**
//  * Filter asynchronous routing tables by recursion
//  * @param routes asyncRoutes
//  * @param roles
//  */
// export function filterAsyncRoutes(routes, roles) {
//   const res = []
//   routes.forEach(route => {
//     const tmp = { ...route }
//     if (hasPermission(roles, tmp)) {
//       if (tmp.children) {
//         tmp.children = filterAsyncRoutes(tmp.children, roles)
//       }
//       res.push(tmp)
//     }
//   })

//   return res
// }

/**
 * 过滤权限路由
 * @param { Arry } routes 路由集合
 * @param { Arry } promissionRoutes 后台权限路由集合
 */
export function filterRoutes(routes, promissionRoutes){
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    const promission = promissionRoutes.find(s => s.url ==tmp.path)
    if (promission) {
      // 按钮权限
      if (!tmp.children) { 
        tmp.meta.permission = promission.permission || [];              
      }
      if (tmp.children && promission.childrenSet) {
        tmp.children = filterRoutes(tmp.children, promission.childrenSet)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  asyncRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ASYNC_ROUTES:(state, data) => {
    state.asyncRoutes = data
  }
}

const actions = {
  getPermission({ commit }){
    return new Promise((resolve) => {
      const async = [
        {
          "name":"menu-permission",
          "url":"/permission",
          "title":"permission",
          "icon":"lock",
          "childrenSet":[
              {
                  "name":"menu-permission-page",
                  "url":"/page",
                  "meta":{
                      "title":"permission",
                      "icon":"lock",
                      //按钮权限 
                      "permission":[
                          1
                      ]
                  }
              }
            ]
          },
          {
            "name":"menu-user",
            "url":"/user",
            "title":"用户管理",
            "icon":"lock",
            "childrenSet":[
              {
                "name":"menu-user-unverified",
                "url":"/unverified",
                "meta":{
                    "title":"未认证用户",
                    "icon":"lock",
                    //按钮权限 id
                    "permission":[
                        1
                    ]
                }
              },
              {
                "name":"menu-user-verified",
                "url":"/verified",
                "meta":{
                    "title":"已认证用户",
                    "icon":"lock",
                    //按钮权限 id
                    "permission":[
                        1
                    ]
                }
              }
            ]
        },
        {
            "name":"nav.order",
            "url":"/order",
            "title":"order",
            "icon":"lock",
            "childrenSet":[
                {
                    "name":"nav.order.index",
                    "url":"/index",
                    "meta":{
                        "title":"order",
                        "icon":"lock",
                        //按钮权限 id
                        "permission":[
                            1
                        ]
                    }
                }
            ]
        },
        {
          "name":"menu-wallet",
          "url":"/wallet",
          "title":"钱包管理",
          "icon":"lock",
          "childrenSet":[
            {
              "name":"menu-wallet-withdraw",
              "url":"/withdraw",
              "meta":{
                "title":"订单列表",
                "icon":"lock",
                //按钮权限 id
                "permission":[
                    1
                ] 
              }
            },
            {
              "name":"menu-wallet-withdraw-detail",
              "url":"/detail/:id(\\d+)",
              "meta":{
                "title":"订单详情",
                "icon":"lock",
                //按钮权限 id
                "permission":[
                    1
                ]
              }
            }
          ]
        },
        {
          "name":"menu-permission",
          "url":"/permission",
          "title":"permission",
          "icon":"lock",
          "childrenSet":[
              {
                  "name":"menu-permission-page",
                  "url":"/page",
                  "meta":{
                      "title":"permission",
                      "icon":"lock",
                      //按钮权限 
                      "permission":[
                          1
                      ]
                  }
              },
              {
                "name":"menu-permission-directive",
                "url":"/directive",
                "meta":{
                    "title":"directivePermission",
                    "icon":"lock",
                    //按钮权限 
                    "permission":[
                        1
                    ]
                }
              }
            ]
          }
      ];
    commit('SET_ASYNC_ROUTES', async)
    resolve(async)

      // getUserPermission()
      //   .then(function(res){
      //     console.log(res)
      //     let async = res.data || [];
      //     console.log(async)
      //     commit('SET_ASYNC_ROUTES', async)
      //     resolve(async)
      //   })
    })
  },
  routerMatch({ commit }, userPermission){
    return new Promise((resolve, reject) => {
      let accessedRoutes= filterRoutes(asyncRoutes, userPermission);
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
